package com.joysuch.wwyt.api.mh.socket;


import com.joysuch.wwyt.bp.websocket.WebSocket;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.util.concurrent.*;


@Slf4j
public class MhWebSocketClientInstance {
    private static final ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 10, 0, TimeUnit.MINUTES,
            new LinkedBlockingQueue<>(100), (r, executor) -> {
        log.error("websocket queue blocked...");
    });


    private String sendIp;
    private Integer sendPort;
    private String sendOpen;

    private static final Map<String, MhWebSocketClient> CLIENT_MAP = new ConcurrentHashMap();

    public static void getWebSocketClientAndSend(String data, String sendOpen, String sendIp, Integer sendPort) {
        executor.execute(() -> {
            if (!"true".equalsIgnoreCase(sendOpen)) {
                log.info("... mh socket sender: mh.monitPoint.socket.open is not open, will not send socket message out.");
                return;
            }
            for (Map.Entry<String, MhWebSocketClient> entry : CLIENT_MAP.entrySet()) {
                log.info("++++++++key{}" + entry.getKey() + "+++++++++++value{}" + entry.getValue());
            }
            String key = getKey(sendIp, sendPort);
            MhWebSocketClient msclient = CLIENT_MAP.get(key);
            if (msclient == null || !msclient.isOpen()) {
                msclient = new MhWebSocketClient(sendIp, sendPort);
                log.info("... new mh socket sender: websocket url {}:{} ", sendIp, sendPort);
                CLIENT_MAP.put(key, msclient);
            }
            boolean result = msclient.send(data);
            int tryCount = 1;
            while (!result && tryCount <= 3) {
                msclient = new MhWebSocketClient(sendIp, sendPort);
                CLIENT_MAP.put(key, msclient);
                result = msclient.send(data);
                log.info("+++++++++++++++++++++++++++++++++重新连接次数"+tryCount+"++++++++++++++++++++++++");
                tryCount++;
            }

        });
//        executor.execute(() -> {
//            if (!"true".equalsIgnoreCase(sendOpen)) {
//                log.info("... mh socket sender: mh.monitPoint.socket.open is not open, will not send socket message out.");
//                return;
//            }
//            if (this.mhWebSocketClient == null || !this.mhWebSocketClient.isOpen()) {
//                try {
//                    this.mhWebSocketClient = new MhWebSocketClient(this.sendIp, this.sendPort);
//                    this.mhWebSocketClient.send(data);
//                    log.info("... mh socket sender: websocket url {}:{} ", sendIp, sendPort);
//                } catch (Exception e) {
//                    log.error("... mh socket sender: init websocket exception ", e);
//                }
//            } else {
//                this.mhWebSocketClient.send(data);
//            }
//        });
    }

    private static String getKey(String sendIp, Integer sendPort) {
        StringBuilder builder = new StringBuilder();
        return builder.append(sendIp).append(":").append(sendPort).toString();
    }

    @PreDestroy
    public void closeClient() {
        for (MhWebSocketClient client : CLIENT_MAP.values()) {
            if (client.isOpen()) {
                client.close();
            }
        }
        if (!executor.isShutdown()) {
            executor.shutdown();
        }
    }
}
